<template>
  <!-- // 修改模板 -->
  <div class="exit-conditions-add">
    <el-dialog v-dialogDrag :close-on-click-modal="false" :visible.sync="dataObj.isShow" title="新增模板" width="70%" @close="cancelDialog">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-tabs v-model="activeName">
          <el-tab-pane label="模板管理" name="first">
            <el-row :gutter="12">
              <el-col :span="24">
                <el-form-item label="模板名称" prop="reportTemplate.tmplName">
                  <el-input v-model="ruleForm.reportTemplate.tmplName" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row >
              <el-col :span="24">
                <el-form-item label="模板文件" prop="reportTemplate.jasperName">
                  <UploadFileSingle :data-obj="uploadDataObj" @getData="getData"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row >
              <el-col :span="24">
                <el-form-item label="描述" prop="reportTemplate.tmplDesc">
                  <el-input v-model="ruleForm.reportTemplate.tmplDesc" type="textarea" placeholder="请输入"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="数据源" name="second">
            <el-row v-for="(item, index) in ruleForm.reportTmplDatasourceRltsList" :key="index" :gutter="12">
              <el-col :span="4">
                <el-form-item
                  :label="'数据源' + (index+1)"
                  :prop="'reportTmplDatasourceRltsList.' + index + '.primaryflag'"
                  :rules="{
                    required: true, message: '请输入参数key', trigger: 'blur'
                  }"
                >
                  <el-radio v-model="item.primaryflag" label="1" @change="changePrimary(item,index)">主键</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="9" class="no-margin">
                <el-form-item
                  v-if="item.primaryflag!=='1'"
                  :prop="'reportTmplDatasourceRltsList.' + index + '.datasourceKey'"
                  :rules="{
                    required: true, message: '请输入参数key', trigger: 'blur'
                  }"
                >
                  <el-input v-model="item.datasourceKey" placeholder="请输入参数key"/>
                </el-form-item>
              </el-col>
              <el-col :span="9" class="no-margin">
                <el-form-item
                  :prop="'reportTmplDatasourceRltsList.' + index + '.datasourceName'"
                  :rules="{
                    required: true, message: '请选择数据源', trigger: 'change'
                  }"
                >
                  <el-input v-model="item.datasourceName" placeholder="请选择数据源" @click.native="selectType(index)"/>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-button @click.prevent="removeDomain(item)">删除</el-button>
              </el-col>
            </el-row>
            <el-row>
              <el-form-item>
                <el-button type="success" @click="addDomain">新增数据源</el-button>
              </el-form-item>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="参数设置" name="third">
            <el-row v-for="(item, index) in ruleForm.reportParaList" :key="index" :gutter="12">
              <el-col :span="9">
                <el-form-item
                  :label="'参数'+(index+1)"
                  :prop="'reportParaList.' + index + '.paraName'"
                  :rules="{
                    required: true, message: '参数不能为空', trigger: 'blur'
                  }"
                >
                  <el-input v-model="item.paraName" placeholder="请输入参数"/>
                </el-form-item>
              </el-col>
              <el-col :span="9" class="no-margin">
                <el-form-item
                  :key="item.key"
                  :prop="'reportParaList.' + index + '.paraDesc'"
                  :rules="{
                    required: true, message: '参数描述不能为空', trigger: 'blur'
                  }"
                >
                  <el-input v-model="item.paraDesc" placeholder="请输入参数描述"/>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-button @click.prevent="removePara(item)">删除</el-button>
              </el-col>
            </el-row>
            <el-row>
              <el-form-item>
                <el-button type="success" @click="addParams">新增参数</el-button>
              </el-form-item>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="默认设置" name="fourth">
            <el-table
              v-loading="tableDeault.loading"
              ref="infoTable"
              :data="tableDeault.tableData"
              height="tableHeight"
              row-key="signKey"
              fit
              border
              element-loading-spinner="el-loading1"
              highlight-current-row
            >
              <!-- <el-table-column :reserve-selection="false" type="selection" width="55" align="center"/> -->
              <el-table-column prop="key" show-overflow-tooltip align="center" label="参数Key" />
              <el-table-column prop="value" show-overflow-tooltip align="center" label="参数值"/>
              <el-table-column prop="name" label="描述" align="center"/>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">关闭</el-button>
        <el-button v-no-more-click type="primary" @click="submitForm('ruleForm')">确定</el-button>
      </span>
      <el-dialog
        :visible.sync="innerVisible"
        width="60%"
        title="选择数据源"
        append-to-body>
        <section class="layer">
          <div class="box">
            <div class="box-header handle">
              <div class="box-body">
                <el-form ref="searchForm" :model="searchForm" label-width="60px">
                  <el-row :gutter="12">
                    <el-col :md="12" :lg="8" :xl="6">
                      <el-form-item label="数据源" prop="taskName">
                        <el-input v-model="searchForm.datasourceName" clearable placeholder="请输入" style="width:100%;" />
                      </el-form-item>
                    </el-col>
                    <el-col :md="12" :lg="8" :xl="6">
                      <el-form-item label="主机地址" prop="taskName">
                        <el-input v-model="searchForm.datasourceUrl" clearable placeholder="请输入" style="width:100%;" />
                      </el-form-item>
                    </el-col>
                    <el-col :md="12" :lg="8" :xl="6">
                      <el-button v-no-more-click type="primary" @click="searchDataSource">查询</el-button>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
              <div class="box-tools"/>
            </div>
            <div class="box-body">
              <el-table
                v-loading="tableSorce.loading"
                ref="infoTable"
                :data="tableSorce.tableData"
                height="230"
                row-key="signKey"
                fit
                border
                element-loading-spinner="el-loading1"
                highlight-current-row
                @current-change="handleCurrentChange"
                @selection-change="getRowData">
                <el-table-column type="index" label="序号" width="50" align="center" />
                <el-table-column prop="datasourceName" show-overflow-tooltip align="center" label="名称" width="200"/>
                <el-table-column prop="datasourceTypeName" show-overflow-tooltip align="center" label="数据源类型" width="160"/>
                <el-table-column prop="" show-overflow-tooltip label="配置内容" align="left">
                  <template slot-scope="scope">
                    <div v-if="scope.row.datasourceTypeName==='JSON'">
                      <div><span style="color: #1B65B9">JSON URL：</span>{{ scope.row.datasourceUrl }}</div>
                      <div><span style="color: #1B65B9">selectExpression：</span>{{ scope.row.selectExpression }}</div>
                    </div>
                    <div v-else>
                      <div><span style="color: #1B65B9">连接URL：</span>{{ scope.row.datasourceUrl }}</div>
                      <div><span style="color: #1B65B9">用户名：</span>{{ scope.row.username }}</div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                :current-page="tableSorce.currentPage"
                :page-sizes="[15, 30, 50, 100]"
                :page-size="tableSorce.pageSize"
                :total="tableSorce.total"
                small
                layout="slot, sizes, prev, pager, next, jumper"
                @current-change="handleCurrentPageChange"
                @size-change="handlePageSizeChange">
                <template slot>
                  <span class="el-pagination__total">{{ `总共${tableSorce.total}条 显示${tableSorce.startRow}-${tableSorce.endRow}条` }}</span>
                </template>
              </el-pagination>
            </div>
          </div>
        </section>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelDialogSorce">关闭</el-button>
          <el-button v-no-more-click type="primary" @click="confrimDataSorce()">确定</el-button>
        </span>
      </el-dialog>
  </el-dialog></div>
</template>

<script>
import UploadFileSingle from '../../../components/UploadFileSingle/index'
import ApiObj from '../../../api/template-management'
import { datasourceGetAllPage } from '../../../api/data-source-management'
export default {
  name: '',
  components: {
    UploadFileSingle
  },
  mixins: [

  ],
  props: {
    dataObj: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      activeName: 'first',
      tableDeault: {
        loading: false,
        tableData: []
      },
      tableSorce: {
        loading: false,
        tableData: [],
        pageNum: 1,
        total: 0,
        pageSize: 15,
        currentPage: 1,
        startRow: 0,
        endRow: 0
      },
      uploadDataObj: {
        jasperName: ''
      },
      // 数据源
      searchForm: {
        datasourceUrl: '',
        datasourceName: ''
      },
      dataSourceSelectList: [],
      dataSourceSelect: {},
      innerVisible: false,
      dataSourceIndex: '',
      ruleForm: {
        reportParaList: [
          {
            paraDesc: '',
            paraName: ''
          }
        ],
        reportTemplate: {
          jasperName: '',
          tmplDesc: '',
          tmplName: ''
        },
        reportTmplDatasourceRltsList: [
          {
            datasourceKey: '',
            datasourceName: '',
            primaryflag: '1'
          }
        ]
      },
      rules: {
        reportTemplate: {
          tmplName: [
            { required: true, message: '请输入模板名称', trigger: 'blur' }
          ],
          jasperName: [
            { required: true, message: '请上传文件', trigger: 'blur' }
          ]
          // tmplDesc: [
          //   { required: true, message: '请输入模板描述', trigger: 'blur' }
          // ]
        }
      }
    }
  },
  computed: {

  },
  watch: {

  },
  created() {
    this.$nextTick(() => {
      this.getDetils()
      this.getDefaultConfigData()
    })
  },
  mounted() {

  },
  methods: {
    // 查询默认设置列表
    getDefaultConfigData() {
      let params = {
        // tmplId: '1'
      }
      ApiObj.getUserPara(params).then(res => {
        if (res.data.code === 0) {
          this.tableDeault.tableData = res.data.data
          // console.log(res.data)
        }
      })
    },
    // 查询数据源
    searchDataSource() {
      this.getDataSource()
    },
    //   查询详情
    getDetils(row) {
      let params = {
        tmplId: this.dataObj.row.tmplId
      }
      ApiObj.templateGetReportTmplDetail(params).then(res => {
        if (res.data.code === 0) {
          this.ruleForm = res.data.data
          this.uploadDataObj.jasperName = this.ruleForm.reportTemplate.jasperName
        }
      })
    },
    // 关闭选择数据源
    cancelDialogSorce() {
      this.innerVisible = false
    },
    // 确认选择行
    confrimDataSorce() {
      console.log(this.dataSourceIndex)
      this.innerVisible = false
      this.$set(this.ruleForm.reportTmplDatasourceRltsList, this.dataSourceIndex, { ...this.ruleForm.reportTmplDatasourceRltsList[this.dataSourceIndex], ...this.dataSourceSelect })
      // this.ruleForm.reportTmplDatasourceRltsList[this.dataSourceIndex] = { ...this.ruleForm.reportTmplDatasourceRltsList[this.dataSourceIndex], ...this.dataSourceSelect }
    },
    // 选择当前行数据源
    handleCurrentChange(val) {
      this.dataSourceSelect = val
    },
    // 选择数据源
    getRowData(val) {
      this.dataSourceSelectList = val
    },
    // 获取数据源列表
    getDataSource() {
      let params = {
        pageNo: this.tableSorce.currentPage,
        pageSize: this.tableSorce.pageSize,
        ...this.searchForm
      }
      this.tableSorce.loading = true
      datasourceGetAllPage(params).then(res => {
        if (res.data.code === 0) {
          this.tableSorce.tableData = res.data.data
          this.tableSorce.total = res.data.data.length
          const startRow = this.tableSorce.pageSize * (this.tableSorce.currentPage - 1) + 1
          const endRow = this.tableSorce.pageSize * this.tableSorce.currentPage > this.tableSorce.total ? this.tableSorce.total : this.tableSorce.pageSize * this.tableSorce.currentPage
          this.tableSorce.startRow = startRow
          this.tableSorce.endRow = endRow
          this.tableSorce.loading = false
        } else {
          this.$alert(res.data.message, {
            type: 'error',
            confirmButtonText: '确定'
          })
          this.tableSorce.loading = false
        }
      })
    },
    // 分页器
    handlePageSizeChange(val) {
      this.tableSorce.pageSize = val
      this.getDataSource()
    },
    handleCurrentPageChange(val) {
      this.tableSorce.currentPage = val
      this.getDataSource()
    },
    // 获取上传文件信息
    getData(data) {
      this.ruleForm.reportTemplate.jasperName = data
    },
    handleSizeChange() {

    },
    // 数据源选择
    selectType(index) {
      this.dataSourceIndex = index
      this.innerVisible = true
      this.getDataSource()
    },
    changePrimary(item, index) {
      console.log(item.primaryflag)
      this.ruleForm.reportTmplDatasourceRltsList.forEach((item, idx) => {
        if (idx !== index) {
          item.primaryflag = '0'
        } else {
          item.primaryflag = '1'
        }
      })
    },
    removeDomain(item) {
      var index = this.ruleForm.reportTmplDatasourceRltsList.indexOf(item)
      if (index === 0) {
        this.$alert(`<div class="myalert-header">操作失败</div>
                <div class="myalert-content">请不要删除最后一项</div>`, {
          dangerouslyUseHTMLString: true, confirmButtonText: '确定',
          type: 'error'
        })
        return
      }
      if (index !== -1) {
        this.ruleForm.reportTmplDatasourceRltsList.splice(index, 1)
      }
    },
    removePara(item) {
      var index = this.ruleForm.reportParaList.indexOf(item)
      if (index === 0) {
        this.$alert(`<div class="myalert-header">操作失败</div>
                <div class="myalert-content">请不要删除最后一项</div>`, {
          dangerouslyUseHTMLString: true, confirmButtonText: '确定',
          type: 'error'
        })
        return
      }
      if (index !== -1) {
        this.ruleForm.reportParaList.splice(index, 1)
      }
    },
    addDomain() {
      this.ruleForm.reportTmplDatasourceRltsList.push({
        datasourceKey: '',
        datasourceName: '',
        primaryflag: '0'
      })
    },
    addParams() {
      this.ruleForm.reportParaList.push({
        paraDesc: '',
        paraName: ''
      })
    },
    cancelDialog() {
      this.$emit('closeModifyDialog')
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let obj = Object.assign({}, this.ruleForm)
          let params = obj
          ApiObj.templateUpdate(params).then(res => {
            if (res.data.code === 0) {
              this.$message({
                type: 'success',
                dangerouslyUseHTMLString: true,
                message: `<strong>操作成功</strong><p>${res.data.message}</p>`,
                duration: 3000
              })
              this.cancelDialog()
            } else {
              this.$alert(`<div class="myalert-header">操作失败</div>
                <div class="myalert-content">${res.data.message}</div>`, {
                dangerouslyUseHTMLString: true, confirmButtonText: '确定',
                type: 'error'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }

}
</script>

<style scoped lang="scss">
 /deep/.el-tabs .el-tabs__content {
  max-height: 358px;
  overflow-y: auto;
  min-height: 300px;
}
.no-margin{
  /deep/.el-form-item__content{
    margin-left:0!important;
  }
}
</style>
